<template>
  <div class="product-page">
    <van-nav-bar
      :title="currentCategory?.categoryName || '商品列表'"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="query.productName"
        placeholder="请输入商品名称"
        show-action
        @search="onSearch"
        @clear="onClear"
      >
        <template #action>
          <div @click="onSearch(query.productName)">搜索</div>
        </template>
      </van-search>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <van-loading v-if="loading" type="spinner" size="24px" vertical />
      <van-empty v-else-if="products.length === 0" description="暂无商品" />
      
      <van-cell-group inset v-else v-for="product in products" :key="product.id" class="product-item">
        <van-cell>
          <template #title>
            <div class="product-info">
              <img :src="getProductImage(product.photo)" class="product-image" />
              <div class="product-detail">
                <div class="product-name">{{ product.productName }}</div>
                <div class="product-price">¥{{ (product.price || 0).toFixed(2) }}</div>
              </div>
              <div class="action-buttons">
                <van-button 
                  plain
                  size="small"
                  type="primary" 
                  class="edit-button"
                  @click="editProduct(product)"
                  :disabled="isProcessing"
                >
                  编辑
                </van-button>
                <van-button 
                  plain
                  size="small"
                  type="danger" 
                  class="delete-button"
                  @click="confirmDelete(product)"
                  :disabled="isProcessing"
                >
                  删除
                </van-button>
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="products.length > 0">
      <van-pagination
        v-model="query.current"
        :total-items="pagination.total"
        :items-per-page="query.size"
        force-ellipses
        @change="onPageChange"
      />
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-actions">
      <van-button 
        round 
        type="primary" 
        icon="plus" 
        @click="addProduct"
      >
        添加商品
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { 
  pageProducts, 
  deleteProduct, 
  getProductById,
  type Product,
  type ProductQuery,
  type PageResult
} from '../api/product'
import { getCategoryDetail, type Category } from '../api/category'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const isProcessing = ref(false)

// 商品数据
const products = ref<Product[]>([])

// 查询条件
const query = ref<ProductQuery>({
  productName: '',
  categoryId: '',
  current: 1,
  size: 10
})

// 分页信息
const pagination = ref({
  total: 0,
  current: 1,
  pages: 0
})

// 当前分类
const currentCategory = ref<Category | null>(null)

// 获取商品图片
const getProductImage = (photo?: string) => {
  if (!photo) return '/products/default.png'
  
  // 如果是完整URL就直接返回
  if (photo.startsWith('http')) {
    return photo
  } 
  // 如果是base64编码
  else if (photo.startsWith('data:image')) {
    return photo
  }
  // 否则拼接服务器地址
  else {
    // 替换为实际的服务器地址
    return `/api/attachment/download?filename=${encodeURIComponent(photo)}`
  }
}

// 查询关键词变化
const onSearch = (val?: string) => {
  query.value.productName = val || ''
  query.value.current = 1 // 重置到第一页
  fetchProducts()
}

// 清空搜索框
const onClear = () => {
  query.value.productName = ''
  query.value.current = 1 // 重置到第一页
  fetchProducts()
}

// 页码变化
const onPageChange = (page: number) => {
  query.value.current = page
  fetchProducts()
}

// 获取当前分类
const getCurrentCategory = async () => {
  const categoryId = route.params.id
  if (categoryId) {
    query.value.categoryId = categoryId
    
    try {
      const category = await getCategoryDetail(categoryId as string)
      if (category) {
        currentCategory.value = category
      }
    } catch (error) {
      console.error('获取分类详情失败:', error)
    }
  }
}

// 获取商品列表
const fetchProducts = async (showLoadingIndicator = true) => {
  if (showLoadingIndicator) {
    loading.value = true
  }
  
  try {
    const result = await pageProducts(query.value)
    products.value = result.records
    pagination.value = {
      total: result.total,
      current: result.current,
      pages: result.pages
    }
  } catch (error) {
    console.error('加载商品数据失败:', error)
    showToast('加载商品数据失败')
  } finally {
    loading.value = false
  }
}

// 编辑商品
const editProduct = (product: Product) => {
  router.push(`/product/edit/${product.id}`)
}

// 添加商品
const addProduct = () => {
  router.push(`/product/add?categoryId=${route.params.id}`)
}

// 确认删除商品
const confirmDelete = (product: Product) => {
  if (isProcessing.value) return
  
  showDialog({
    title: '确认删除',
    message: `确定要删除商品"${product.productName}"吗？`,
    showCancelButton: true,
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
    cancelButtonText: '取消'
  }).then(async () => {
    isProcessing.value = true
    
    try {
      // 乐观更新UI
      const tempProducts = [...products.value]
      products.value = products.value.filter(item => item.id !== product.id)
      
      // 执行删除逻辑
      const success = await deleteProduct(product.id)
      
      if (success) {
        showToast({
          type: 'success',
          message: '删除成功',
          position: 'bottom'
        })
      } else {
        // 删除失败，恢复数据
        products.value = tempProducts
        showToast({
          type: 'fail',
          message: '删除失败',
          position: 'bottom'
        })
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      // 删除失败，重新加载数据
      fetchProducts(false)
    } finally {
      isProcessing.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

onMounted(async () => {
  await getCurrentCategory()
  fetchProducts()
})
</script>

<style lang="scss" scoped>
.product-page {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;
  padding-bottom: 80px;

  .search-bar {
    padding: 8px 0;
    background-color: #fff;
  }

  .product-list {
    flex: 1;
    padding: 12px;

    .product-item {
      margin-bottom: 12px;
    }
  }

  .product-info {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .product-image {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
  }

  .product-detail {
    flex: 1;
  }

  .product-name {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px;
  }

  .product-price {
    color: #ee0a24;
    font-size: 14px;
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    margin-left: auto;

    .van-button {
      min-width: 56px;
    }
  }

  .empty-state {
    padding: 40px 0;
  }

  .bottom-actions {
    padding: 16px;
    background: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: center;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    margin-bottom: 70px;
  }
}
</style> 